import 'package:flutter/material.dart';

class Page extends StatefulWidget {
  const Page({super.key, required this.text});

  final String text;

  @override
  State<Page> createState() => _PageState();
}

class _PageState extends State<Page> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用
    print("build ${widget.text}");
    return Center(
      child: Text(
        widget.text,
        textScaleFactor: 5,
      ),
    );
  }

  @override
  bool get wantKeepAlive => true; // 是否需要缓存
}

class PageCacheViewDemo extends StatelessWidget {
  const PageCacheViewDemo({super.key});

  @override
  Widget build(BuildContext context) {
    var children = <Widget>[];
    // 生成6个tab页
    for (var i = 0; i < 6; i++) {
      children.add(Page(text: 'Page $i'));
    }

    return Scaffold(
      appBar: AppBar(
        title: const Text('Tab切换缓存'),
      ),
      body: PageView(
        // scrollDirection: Axis.vertical, // 滑动方向为垂直方向
        allowImplicitScrolling: true, // 预渲染模式
        children: children,
      ),
    );
  }
}
